package org.edu.modules.kwgl.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.edu.common.system.base.controller.BaseController;
import org.edu.common.api.vo.Result;
import org.edu.common.system.query.QueryGenerator;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.oConvertUtils;
import org.edu.modules.kwgl.api.CommonApi;
import org.edu.modules.kwgl.api.IVeJwJxzyFeignClientService;
import org.edu.modules.kwgl.config.ConfigConstant;
import org.edu.modules.kwgl.entity.*;
import org.edu.modules.kwgl.service.IVeJwBkXueshengService;
import org.edu.modules.kwgl.service.IVeJwChengjiService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.edu.modules.kwgl.service.IVeJwCjBukaoService;
import org.edu.modules.kwgl.service.IVeJwKaoshiService;
import org.edu.modules.kwgl.utils.CommonAipUtils;
import org.edu.modules.kwgl.utils.JwTextUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.edu.common.aspect.annotation.AutoLog;

/**
 * @Description: 成绩
 * @Author: jeecg-boot
 * @Date: 2021-05-12
 * @Version: V1.0
 */
@Api(tags = "成绩")
@RestController
@RequestMapping("/kwgl/veJwChengji")
@Slf4j
public class VeJwChengjiController extends BaseController<VeJwChengji, IVeJwChengjiService> {
    @Autowired
    private IVeJwChengjiService veJwChengjiService;

    @Autowired
    private IVeJwBkXueshengService veJwBkXueshengService;

    @Autowired
    private IVeJwKaoshiService veJwKaoshiService;

    @Autowired
    IVeJwJxzyFeignClientService veJwJxzyFeignClientService;

    @Autowired
    CommonApi commonApi;

    private MultipartHttpServletRequest multipartRequest;

    /**
     * 分页列表查询
     * @param veJwChengji
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "成绩-分页列表查询")
    @ApiOperation(value = "成绩-分页列表查询", notes = "成绩-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(VeJwChengji veJwChengji,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<VeJwChengji> queryWrapper = QueryGenerator.initQueryWrapper(veJwChengji, req.getParameterMap());
        Page<VeJwChengji> page = new Page<VeJwChengji>(pageNo, pageSize);
        IPage<VeJwChengji> pageList = veJwChengjiService.page(page, queryWrapper);

        //查询是否加入补考名单
        for (VeJwChengji item : pageList.getRecords()) {
            if (veJwBkXueshengService.getByStuidAndKcid(item.getStuid(), item.getKcid()) == null) {
                item.setIsJoinBk(0);
            } else {
                item.setIsJoinBk(1);
            }
            item.setAudittidText(JwTextUtils.getText(item.getAudittid()));
        }
        return Result.ok(pageList);
    }


    /**
     * 学生录入信息查询
     *
     * @param veJwChengji
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "成绩-学生录入信息查询")
    @ApiOperation(value = "成绩-学生录入信息查询", notes = "成绩-学生录入信息查询")
    @GetMapping(value = "/lrlist")
    public Result<?> lrlist(VeJwChengji veJwChengji,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        VeJwKaoshi jwKaoshi = veJwKaoshiService.getById(veJwChengji.getKsid());
        LambdaQueryWrapper<VeJwChengji> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VeJwChengji::getKsid, veJwChengji.getKsid());
        List<VeJwChengji> dataList = veJwChengjiService.list(queryWrapper);
        Map<String, VeJwChengji> chengjiMap = new HashMap<>();
        for (VeJwChengji item : dataList) {
            chengjiMap.put(item.getXh(), item);
        }
//        String kcmc=veJwJxzyFeignClientService.getKcNameById(jwKaoshi.getKcid());
        List<VeJwChengji> exportList = new ArrayList<>();
        if (jwKaoshi != null && jwKaoshi.getBjid() != null) {
            for (String xzbId : jwKaoshi.getBjid().split(",")) {
                if (StringUtils.isEmpty(xzbId)) {
                    continue;
                }
                JSONArray objectList = CommonAipUtils.getXueshengByBjid(Integer.valueOf(xzbId));
                if (objectList != null && objectList.size() > 0) {
                    for (int i = 0; i < objectList.size(); i++) {
                        JSONObject student = objectList.getJSONObject(i);
                        VeJwChengji zhiye = new VeJwChengji();
                        zhiye.setXh(student.getString("xh"));
                        zhiye.setXm(student.getString("xm"));
                        zhiye.setFalid(student.getInteger("fal_id"));
                        zhiye.setXzbid(student.getInteger("bj_id"));
                        zhiye.setGradeid(student.getInteger("grade_id"));
                        zhiye.setSpecid(student.getInteger("spec_id"));
                        zhiye.setXzid(student.getInteger("xz"));
                        zhiye.setTerminalid(student.getInteger("terminal_id"));
                        zhiye.setStuid(student.getInteger("id"));
                        zhiye.setKcid(jwKaoshi.getKcid());
                        zhiye.setKsid(jwKaoshi.getId());
                        if (chengjiMap.containsKey(zhiye.getXh())) {
                            exportList.add(chengjiMap.get(zhiye.getXh()));
                        }else {
                            exportList.add(zhiye);
                        }
                    }
                }
            }
        }
        return Result.ok(exportList);
    }

    /**
     * 添加
     *
     * @param veJwChengji
     * @return
     */
    @AutoLog(value = "成绩-添加")
    @ApiOperation(value = "成绩-添加", notes = "成绩-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody VeJwChengji veJwChengji) {
        veJwChengjiService.save(veJwChengji);
        return Result.ok("添加成功！");
    }

    /**
     * 批量通过
     *
     * @param jsonObject
     * @return
     */
    @AutoLog(value = "成绩类型-通过")
    @ApiOperation(value = "成绩类型-通过", notes = "成绩类型-通过")
    @PutMapping(value = "/stateBatch")
    public Result<?> stateBatch(@RequestBody JSONObject jsonObject) {
        if (!jsonObject.containsKey("ids")) {
            return Result.error("参数错误!");
        }
        String ids = jsonObject.getString("ids");
        VeJwChengji data = new VeJwChengji();
        data.setAuditstatus(ConfigConstant.AUDIT_AGREE);
        LambdaQueryWrapper<VeJwChengji> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(VeJwChengji::getId, Arrays.asList(ids.split(",")));
        veJwChengjiService.update(data, queryWrapper);
        return Result.ok("通过成功");
    }


    /**
     * 编辑
     *
     * @param veJwChengji
     * @return
     */
    @AutoLog(value = "成绩-编辑")
    @ApiOperation(value = "成绩-编辑", notes = "成绩-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody VeJwChengji veJwChengji) {
        VeJwChengji old = veJwChengjiService.getById(veJwChengji.getId());
        if (old == null) {
            return Result.error("记录不存在!");
        }
        if (old.getAuditstatus() == ConfigConstant.AUDIT_AGREE) {
            return Result.error("记录已审核!");
        }
        //若无关联考试成绩置为0
        if (veJwChengji.getHasexam() == 0) {
            veJwChengji.setKccj(new BigDecimal(0.0));
        }
        //如果是考试形式为【考试】
        if (veJwChengji.getKsxsid() == 1) {
            //分数超过100置为0
            if (veJwChengji.getKccj().compareTo(new BigDecimal("100.0")) > 1) {
                veJwChengji.setKccj(new BigDecimal("0.0"));
            }
        }
        veJwChengjiService.updateById(veJwChengji);
        return Result.ok("编辑成功!");
    }

    /**
     * 审核
     *
     * @param veJwChengji
     * @return
     */
    @AutoLog(value = "成绩-审核")
    @ApiOperation(value = "成绩-审核", notes = "成绩-审核")
    @PutMapping(value = "/audit")
    public Result<?> audit(@RequestBody VeJwChengji veJwChengji) {
        VeJwChengji old = veJwChengjiService.getById(veJwChengji.getId());
        if (old == null) {
            return Result.error("记录不存在!");
        }
//		 if(old.getAuditstatus() == ConfigConstant.AUDIT_AGREE){
//			 return Result.error("记录已审核!");
//		 }
        VeJwChengji data = new VeJwChengji();
        data.setId(old.getId());
        if (veJwChengji.getAudittidText() != null) {
            data.setAudittid(JwTextUtils.addText(veJwChengji.getAudittidText()));
        }
        data.setAuditstatus(veJwChengji.getAuditstatus());
        veJwChengjiService.updateById(data);
        return Result.ok("处理成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "成绩-通过id删除")
    @ApiOperation(value = "成绩-通过id删除", notes = "成绩-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        veJwChengjiService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "成绩-批量删除")
    @ApiOperation(value = "成绩-批量删除", notes = "成绩-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.veJwChengjiService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "成绩-通过id查询")
    @ApiOperation(value = "成绩-通过id查询", notes = "成绩-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        VeJwChengji veJwChengji = veJwChengjiService.getById(id);
        if (veJwChengji == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(veJwChengji);
    }


    /**
     * 根据班级id获取班级成绩情况
     *
     * @param bjid
     * @return
     */
    @AutoLog(value = "成绩-通过id查询")
    @ApiOperation(value = "成绩-通过id查询", notes = "成绩-通过id查询")
    @GetMapping(value = "/queryClassCj")
    public Result<?> queryClassCj(@RequestParam(name = "bjid", required = true) Integer bjid,
                               @RequestParam(name = "gradeid", required = false) String gradeid,
                               @RequestParam(name = "semid", required = true) String semid
    ) {
        LambdaQueryWrapper<VeJwChengji> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(VeJwChengji::getGradeid,gradeid);
        queryWrapper.eq(VeJwChengji::getSemid,semid);
        queryWrapper.eq(VeJwChengji::getXzbid,bjid);
        List<VeJwChengji> chengjiList = veJwChengjiService.list(queryWrapper);

        List<JSONObject> kechengList= new ArrayList<>();
        Map<Integer,String> kcMap=new HashMap<>();
        Map<Integer,JSONObject> kechengInfo=new HashMap<>();
        Map map=new HashMap();
        if(chengjiList.size()>0){
            for(VeJwChengji item:chengjiList){
                if(!kcMap.containsKey(item.getKcid())){
                    kcMap.put(item.getKcid(),veJwJxzyFeignClientService.getKcNameById(item.getKcid()));
                    JSONObject kechengJson=new JSONObject();
                    kechengJson.put("id",item.getKcid());
                    kechengJson.put("name",kcMap.get(item.getKcid()));
                    kechengList.add(kechengJson);
                }
                if(!kechengInfo.containsKey(item.getKcid())){
                    kechengInfo.put(item.getKcid(),new JSONObject());
                }
                kechengInfo.get(item.getKcid()).put(item.getXh(),item.getKccj());
            }
        }
        map.put("kechengList",kechengList);
        map.put("kechengInfo",kechengInfo);
        return Result.ok(map);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param veJwChengji
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, VeJwChengji veJwChengji) {
        return super.exportXls(request, veJwChengji, VeJwChengji.class, "成绩");
    }


    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, VeJwChengji.class);
    }


    /**
     * 批量更新成绩
     *
     * @param list
     * @return
     */
    @AutoLog(value = "考试成绩管理-批量更新成绩")
    @ApiOperation(value = "考试成绩管理-批量更新成绩", notes = "考试成绩管理-批量更新成绩")
    @PutMapping(value = "/updateCjBatch")
    public Result<?> updateCjBatch(@RequestBody List<VeJwChengji> list) {

        //获取课程总分
        BigDecimal ksfs = new BigDecimal(veJwJxzyFeignClientService.getKcKsfsById(list.get(0).getKcid()));

        //及格分数
        BigDecimal jgfs = ksfs.multiply(new BigDecimal("0.6"));
//		 List<VeJwChengji> bkcjs = list.stream().filter(item -> item.getKccj()
//				 .compareTo(ksfs)<=0).collect(Collectors.toList());

//		 if(bkcjs.size()<list.size()){
//			 return Result.error("学生成绩不得大于课程总分！请检查！");
//		 }

        for (VeJwChengji item : list) {
            if (item.getKccj() != null) {
                if (item.getKccj().compareTo(ksfs) > 0) {
                    return Result.error("学生成绩不得大于课程总分！请检查！");
                }
                if (item.getKccj().compareTo(jgfs) >= 0) {
                    item.setSfjg(1);
                } else {
                    item.setSfjg(0);
                }
            }

        }
        veJwChengjiService.saveOrUpdateBatch(list);

        return Result.ok("考试成绩提交成功!");
    }


    /**
     * 导出excel
     *
     * @param request
     * @param veJwChengji
     */
    @RequestMapping(value = "/exportXlsKaoshi")
    public ModelAndView exportXlsKaoshi(HttpServletRequest request, VeJwChengji veJwChengji) {
        VeJwKaoshi jwKaoshi = veJwKaoshiService.getById(veJwChengji.getKsid());

        LambdaQueryWrapper<VeJwChengji> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VeJwChengji::getKsid, veJwChengji.getKsid());
        List<VeJwChengji> dataList = veJwChengjiService.list(queryWrapper);
        Map<String, VeJwChengji> chengjiMap = new HashMap<>();
        for (VeJwChengji item : dataList) {
            chengjiMap.put(item.getXh(), item);
        }


        String kcmc=veJwJxzyFeignClientService.getKcNameById(jwKaoshi.getKcid());

        List<VeJwChengji> exportList = new ArrayList<>();
        if (jwKaoshi != null && jwKaoshi.getBjid() != null) {
            for (String xzbId : jwKaoshi.getBjid().split(",")) {
                if (StringUtils.isEmpty(xzbId)) {
                    continue;
                }
                JSONArray objectList = CommonAipUtils.getXueshengByBjid(Integer.valueOf(xzbId));
                if (objectList != null && objectList.size() > 0) {
                    for (int i = 0; i < objectList.size(); i++) {
                        JSONObject student = objectList.getJSONObject(i);
                        VeJwChengji zhiye = new VeJwChengji();
                        zhiye.setStuid(student.getInteger("id"));
                        zhiye.setXh(student.getString("xh"));
                        zhiye.setXm(student.getString("xm"));
                        zhiye.setFalid(student.getInteger("fal_id"));
                        zhiye.setXzbid(student.getInteger("bj_id"));
                        zhiye.setGradeid(student.getInteger("grade_id"));
                        zhiye.setSpecid(student.getInteger("spec_id"));
                        zhiye.setXzid(student.getInteger("xz"));
                        zhiye.setTerminalid(student.getInteger("terminal_id"));


                        exportList.add(zhiye);
                    }
                }
            }
        }

        List<VeJwChengjiExcel> array = new ArrayList<>();
//		map存key减少重复查询
        Map<Integer, String> zybMap = CommonAipUtils.getZybIdNameMap();
        Map<Integer, String> njMap = CommonAipUtils.getGradeIdNameMap();
        Map<Integer, String> xqMap = CommonAipUtils.getXueqiIdName();
        Map<Integer, String> zyMap = new HashMap<>();
        Map<Integer, String> banjiMap = new HashMap<>();

        Map<Integer, String> zyrzmcMap = new HashMap<>();
        for (VeJwChengji item : exportList) {
            VeJwChengjiExcel excelItem = new VeJwChengjiExcel();


            excelItem.setXh(item.getXh());
            excelItem.setXm(item.getXm());

//			专业部名称
            if (item.getFalid() != null && zybMap.containsKey(item.getFalid())) {
                excelItem.setFalidName(zybMap.get(item.getFalid()));
            }
//			年级名称
            if (item.getGradeid() != null && njMap.containsKey(item.getGradeid())) {
                excelItem.setGradeidName(njMap.get(item.getGradeid()));
            }
//			获取专业名称
            if (item.getSpecid() != null) {
                if (!zyMap.containsKey(item.getSpecid())) {
                    zyMap.put(item.getSpecid(), CommonAipUtils.getZyById(item.getSpecid()));
                }
                excelItem.setSpecidName(zyMap.get(item.getSpecid()));
            }

            if (chengjiMap.containsKey(item.getXh())) {
                excelItem.setCjidName(chengjiMap.get(item.getXh()).getKccj().toString());
                excelItem.setCj(chengjiMap.get(item.getXh()).getSfjg() == 1 ? "通过" : "不通过");
            }
//			获取专业名称
            if (item.getSemid() != null && xqMap.containsKey(item.getSemid())) {
                excelItem.setSemidName(xqMap.get(item.getSemid()));
            }


            excelItem.setKcidName(kcmc);

            array.add(excelItem);
        }


        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject("fileName", "成绩");
        mv.addObject("entity", VeJwChengjiExcel.class);
        mv.addObject("params", new ExportParams("成绩报表", "导出人:" + sysUser.getRealname(), "成绩"));
        mv.addObject("data", array);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcelKaoshi", method = RequestMethod.POST)
    public Result<?> importExcelKaoshi(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        String ksid = request.getParameter("ksid");
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Iterator var6 = fileMap.entrySet().iterator();
        if (var6.hasNext()) {
            Map.Entry<String, MultipartFile> entity = (Map.Entry) var6.next();
            MultipartFile file = (MultipartFile) entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);

            Result var11;
            try {
                VeJwKaoshi jwKaoshi = veJwKaoshiService.getById(Integer.parseInt(ksid));
                //map存key减少重复查询
                Map<String, Integer> zybMap = CommonAipUtils.getZybNameIdMap();
                Map<Integer, String> njMap = CommonAipUtils.getGradeIdNameMap();
                Map<Integer, String> zyMap = new HashMap<>();
                Map<Integer, String> banjiMap = new HashMap<>();

                List<VeJwChengjiExcel> list = ExcelImportUtil.importExcel(file.getInputStream(), VeJwChengjiExcel.class, params);
                long start = System.currentTimeMillis();
                List<VeJwChengji> targetList = new ArrayList<>();
                int success = 0;
                int error = 0;
                for (VeJwChengjiExcel item : list) {
                    VeJwChengji zhiye = getCjByXhAndKs(item.getXh(), item.getXm(), Integer.parseInt(ksid));
//					不存在旧数据就新建
                    if (zhiye == null) {
                        zhiye = new VeJwChengji();
                        JSONObject student = CommonAipUtils.getXueshengByXh(item.getXh(), item.getXm());
                        if (student == null) {
                            error++;
                            continue;
                        }
                        zhiye.setXh(item.getXh());
                        zhiye.setXm(item.getXm());
                        zhiye.setStuid(student.getInteger("id"));
                        zhiye.setAuditstatus(0);
                        zhiye.setFalid(student.getInteger("fal_id"));
                        zhiye.setXzbid(student.getInteger("bj_id"));
                        zhiye.setGradeid(student.getInteger("grade_id"));
                        zhiye.setSpecid(student.getInteger("spec_id"));
                        zhiye.setXzid(student.getInteger("xz"));
                        zhiye.setTerminalid(student.getInteger("terminal_id"));
                        zhiye.setCjlrrqsj(new Date());
                        zhiye.setKsid(jwKaoshi.getId());
                        zhiye.setKcid(jwKaoshi.getKcid());
                        zhiye.setSemid(jwKaoshi.getSemid());
                    }
                    if(StringUtils.isNotEmpty(item.getCjidName())) {
                        zhiye.setKccj(new BigDecimal(item.getCjidName()));
                    }
                    if(StringUtils.isNotEmpty(item.getCj())){
                        zhiye.setSfjg(item.getCj().trim().equals("通过") ? 1 : 0);
                    }
                    targetList.add(zhiye);
                    success++;
                }
                this.veJwChengjiService.saveOrUpdateBatch(targetList);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                if (error == 0) {
                    return Result.ok("文件导入成功！数据行数：" + targetList.size());
                } else {
                    return Result.ok("文件导入成功！成功" + success + "条，失败" + error + "条");
                }
            } catch (Exception var23) {
                log.error(var23.getMessage(), var23);
                var11 = Result.error("文件导入失败:" + var23.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException var22) {
                    var22.printStackTrace();
                }

            }

            return var11;
        } else {
            return Result.error("文件导入失败！");
        }
    }

    /**
     * 学生成绩统计-成绩查询
     * @param veJwChengji 查询条件
     * @param pageNo 页号
     * @param pageSize 页显示数
     * @param req 请求流
     * @return 成绩列表
     */
    @AutoLog(value = "学生成绩统计-成绩查询")
    @ApiOperation(value = "学生成绩统计-成绩查询", notes = "学生成绩统计-成绩查询")
    @GetMapping("/pageList")
    public Result<?> queryList(VeJwChengji veJwChengji,
                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                               HttpServletRequest req){
        QueryWrapper<VeJwChengji> queryWrapper = QueryGenerator.initQueryWrapper(veJwChengji, req.getParameterMap());
        // 审核状态：通过
        queryWrapper.eq("auditstatus", 1);
        // 根据学号进行排序
        queryWrapper.getExpression().getOrderBy().clear();
        queryWrapper.orderByAsc("xh");

        Page<VeJwChengji> page = new Page<>(pageNo, pageSize);
        IPage<VeJwChengji> pageList = veJwChengjiService.page(page, queryWrapper);

        return Result.OK(pageList);
    }

    /**
     * 学生成绩统计-及格率统计
     * @param veJwChengji 查询条件
     * @return
     */
    @AutoLog(value = "学生成绩统计-及格率统计")
    @ApiOperation(value = "学生成绩统计-及格率统计", notes = "学生成绩统计-及格率统计")
    @GetMapping("/statistics")
    public Result<?> statistics(VeJwChengji veJwChengji){
        // 必须传入学期
        if(veJwChengji == null || veJwChengji.getSemid() == null){
            return Result.error("请选择学期");
        }
        // 获取所有的专业组
        List<JSONObject> zyzList = commonApi.queryFacultyList(CommonApi.COMMON_TOKEN_KEY).getResult();
        List<JSONObject> zyzs = Lists.newArrayList();
        for (JSONObject zyz : zyzList){
            if(Objects.equals(zyz.getInteger("id"), veJwChengji.getFalid()) || veJwChengji.getFalid() == null){
                zyz.put("jgl", veJwChengjiService.caleJgl(veJwChengji, zyz.getInteger("id")));
                zyzs.add(zyz);
            }
        }

        return Result.OK(zyzs);
    }

    /**
     * 学生成绩统计-及格率趋势
     * @return
     */
    @AutoLog(value = "学生成绩统计-及格率趋势")
    @ApiOperation(value = "学生成绩统计-及格率趋势", notes = "学生成绩统计-及格率趋势")
    @GetMapping("/trend")
    public Result<?> trend(VeJwChengji veJwChengji){

        Map<String, JSONObject> data = veJwChengjiService.queryAllJgl();
        // 返回数据
        JSONObject result = new JSONObject();
        // 添加所有学期
        result.put("xqs", commonApi.querySemesterList(CommonApi.COMMON_TOKEN_KEY).getResult());
        // 获取所有的专业组
        List<JSONObject> zyzs = commonApi.queryFacultyList(CommonApi.COMMON_TOKEN_KEY).getResult();
        for(JSONObject zyz : zyzs){
            List<JSONObject> xqs = commonApi.querySemesterList(CommonApi.COMMON_TOKEN_KEY).getResult();
            for (JSONObject xq : xqs){
                JSONObject jglData = data.get(zyz.getInteger("id") + "_" + xq.getInteger("id"));
                // 如果不存在该专业组该学期的及格率数据，则直接赋值为0
                if(jglData == null){
                    xq.put("jgl", 0);
                    continue;
                }
                xq.put("jgl", jglData.getBigDecimal("jgl"));
            }
            zyz.put("xqs", xqs);
        }
        result.put("zyzs", zyzs);
        return Result.OK(result);
    }

    private VeJwChengji getCjByXhAndKs(String xh, String xm, Integer ksid) {
        if (org.springframework.util.StringUtils.isEmpty(xm)) {
            return null;
        }
        LambdaQueryWrapper<VeJwChengji> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VeJwChengji::getXm, xm);
        queryWrapper.eq(VeJwChengji::getXh, xh);
        queryWrapper.eq(VeJwChengji::getKsid, ksid);
        queryWrapper.last(" limit 1 ");
        return veJwChengjiService.getOne(queryWrapper);
    }
}
